package bingo.filter;

import java.io.IOException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.beetl.core.GroupTemplate;
import org.beetl.core.exception.ScriptEvalError;
import org.beetl.ext.servlet.ServletGroupTemplate;
import org.beetl.ext.web.SimpleCrossFilter;

import bingo.util.MobileUtil;
import bingo.util.beetl.TerminalWebRender;



/**
 * Servlet Filter implementation class HTMLFilter
 */
public class HTMLFilter extends SimpleCrossFilter implements Filter {

	public void init(FilterConfig arg0) throws ServletException {

	}

	public void doFilter(ServletRequest request, ServletResponse response,
			FilterChain chain) throws IOException, ServletException {
		
		HttpServletRequest req = (HttpServletRequest) request;
		HttpServletResponse rsp = (HttpServletResponse) response;
		
		rsp.setContentType("text/html;charset=utf-8");
		MobileUtil.initMobileStatus(req);
		
		if (canProcceed(req, response)) {
			String path = req.getServletPath();
			String valueFile = getValueFile(path, req, rsp);
			String ajax = null;
			GroupTemplate gt = getGroupTemplate();

			TerminalWebRender render = new TerminalWebRender(gt);
			Map paras = this.getScriptParas(req, rsp);

			String commonFile = getCommonValueFile(req, rsp);
			Map commonData = new HashMap(), data = new HashMap();
			try {
				if (gt.getResourceLoader().exist(commonFile)) {
					commonData = gt.runScript(commonFile, paras);

				}

				if (gt.getResourceLoader().exist(valueFile)) {
					data = gt.runScript(valueFile, paras);
					if(data.containsKey("json")){
						//认为是json
						rsp.setContentType("text/json;charset=utf-8");
						rsp.getWriter().write((String)data.get("json"));
						return ;
					}
					if(data.containsKey("ajax")){
						ajax = (String)data.get("ajax");
					}
				}

			} catch (ScriptEvalError e) {
				throw new RuntimeException("伪模型脚本有错！", e);
			}

			commonData.putAll(data);
			Iterator it = commonData.keySet().iterator();
			while (it.hasNext()) {
				String key = (String) it.next();
				Object value = commonData.get(key);
				setValue(key, value, req);
			}

			String renderPath = getRenderPath(path, req, rsp);
			if(ajax!=null){
				renderPath = renderPath+"#"+ajax;
			}

			render.render(renderPath, req, rsp);
		} else {

			chain.doFilter(request, response);
		}

	}

	@Override
	protected GroupTemplate getGroupTemplate() {
		return ServletGroupTemplate.instance().getGroupTemplate();
	}
	
	protected boolean canProcceed(ServletRequest req, ServletResponse rsp)
	{
		HttpServletRequest request = (HttpServletRequest)req;
		HttpServletResponse response = (HttpServletResponse)rsp;
		String path = request.getServletPath();		
		String valueFile = getValueFile(path, request, response);
		GroupTemplate gt = getGroupTemplate();
		//交给controoler处理，而不是模拟的后台代码
		if (gt.getResourceLoader().exist(valueFile)) {
			return true;
		}else{
			return false;
		}
	}
	
	@Override
	protected String getValueFile(String path, HttpServletRequest req, HttpServletResponse response)
	{
		String query = req.getQueryString();
		String method = req.getMethod();	
		
		if(query==null||query.length()==0){
			if(method.equalsIgnoreCase("POST")){
				return "/values/" + path + ".post.var";
			}else{
				return "/values/" + path + ".var";
			}
			
		}else{
			if(method.equalsIgnoreCase("POST")){
				return "/values/" + path + "_"+query+".post.var";
			}else{
				return "/values/" + path +"_"+query+ ".var";
			}
		}
		
	}

}